<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-input-restrict
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位" prop="postIds">
        <el-select
          v-model="queryParams.postIds"
          placeholder="岗位"
          filterable
          style="width: 200px"
        >
          <el-option label="全部" :value="undefined" />
          <el-option
            v-for="dict in postOptions"
            :key="dict.postId"
            :label="dict.postName"
            :value="dict.postId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <div
        class="radio"
        v-if="isManager($store.getters.roles) || isProfessional"
      >
        <el-radio-group
          v-model="queryParams.dataScope"
          @change="getList()"
          size="mini"
        >
          <el-radio-button label="0">全部课程</el-radio-button>
          <el-radio-button label="1">我的课程</el-radio-button>
        </el-radio-group>
      </div>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div class="commonMenu rela">
      <el-menu
        default-active=""
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <!-- 0待提交1待审核2已驳回3已通过，null就是全部 -->
        <el-menu-item index="">全部</el-menu-item>
        <el-menu-item index="0">待提交</el-menu-item>
        <el-menu-item index="1">品控/培训专员待审核</el-menu-item>
        <el-menu-item index="2">专业人员待审核</el-menu-item>
        <el-menu-item index="3">品控经理待审核</el-menu-item>
        <el-menu-item index="4">副总经理待审核</el-menu-item>
        <el-menu-item index="-1">已驳回</el-menu-item>
        <el-menu-item index="5">已审核</el-menu-item>
      </el-menu>
    </div>

    <el-table v-loading="loading" :data="postList">
      <el-table-column
        show-overflow-tooltip
        label="课程名称"
        align="center"
        prop="courseName"
      />
      <!-- <el-table-column width="50" label="序号" align="center" prop="">
        <template slot-scope="scope">
          {{
            scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize
          }}
        </template>
      </el-table-column> -->
      <!-- 课程封面 -->
      <el-table-column width="120" label="封面" align="center" prop="coursePic">
        <template slot-scope="scope">
          <el-image
            :src="
              scope.row.coursePic
                ? scope.row.coursePic
                : 'https://oss.metaxun.com/wx/zy/nocourse.png'
            "
            fit="cover"
            :width="120"
          />
        </template>
      </el-table-column>
      <!-- /* 查询课程列表 0.已审核 1.禁用 2.待提交 3.待初审核 4.待复审核 5.已驳回 */
        /* 查询课程列表 0.已启用 1.已停用 */ -->
      <el-table-column label="课时(h)" align="center" prop="studyTime">
        <template slot-scope="scope">
          {{ scope.row.studyTime ? scope.row.studyTime : "--" }}
        </template>
      </el-table-column>
      <el-table-column label="岗位" align="center" prop="postNames" />
      <el-table-column
        label="创建人"
        align="center"
        prop="creatorName"
        v-if="queryParams.dataScope == '0'"
      />

      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间" align="center" prop="updateTime"
        ><template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="postNames"
        v-if="queryParams.status == ''"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0">待提交</el-tag>
          <el-tag v-if="scope.row.status == 5" type="success">已审核</el-tag>
          <el-tag v-if="scope.row.status == 1" type="warning"
            >待品控/培训专员待审核</el-tag
          >
          <el-tag v-if="scope.row.status == 2" type="warning"
            >待专业人员待审核</el-tag
          >
          <el-tag v-if="scope.row.status == 4" type="warning"
            >待副总经理待审核</el-tag
          >
          <el-tag v-if="scope.row.status == 3" type="warning"
            >待品控经理待审核</el-tag
          >
          <el-tag v-if="scope.row.status == -1" type="danger">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row, 'detail')"
            >课程详情</el-button
          >

          <!-- 自己的课程能编辑  待审核 已审核 已驳回的课程可以编辑  -->

          <el-button
            v-if="
              scope.row.creatorId == $store.getters.userId &&
              (scope.row.status == -1 ||
                scope.row.status == 5 ||
                scope.row.status == 0)
            "
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>

          <!-- 复制 草稿都可以复制 必须是自己的课程才能复制-->

          <el-button
            v-if="scope.row.creatorId == $store.getters.userId"
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleCopy(scope.row)"
          >
            复制
          </el-button>
          <!-- 提交审核/同步到正式课-->

          <el-button
            v-if="
              returnSubmit(scope.row, 'show') &&
              (scope.row.status == 0 || scope.row.status == -1)
            "
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="
              handleSubmitAudit(scope.row, returnSubmit(scope.row, 'lable'))
            "
          >
            {{ returnSubmit(scope.row, "lable") }}
          </el-button>
          <!-- 撤销审核 -->
          <el-button
            v-if="
              scope.row.creatorId == $store.getters.userId &&
              scope.row.status > 0 &&
              scope.row.status < 5
            "
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleCancelAudit(scope.row)"
          >
            撤销审核
          </el-button>
          <!-- 审核流程-->
          <el-button
            v-if="returnAudit(scope.row, 'show')"
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleAudit(scope.row)"
          >
            审核
          </el-button>
          <el-button
            v-if="scope.row.status == -1"
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleReason(scope.row)"
          >
            驳回原因
          </el-button>
          <el-button
            v-if="
              scope.row.creatorId == $store.getters.userId &&
              (scope.row.status == -1 ||
                scope.row.status == 2 ||
                scope.row.status == 5 ||
                scope.row.status == 0)
            "
            icon="el-icon-delete"
            size="mini"
            type="text"
            style="color: #e95756"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <rejectDia
      :type="3"
      :open.sync="rejectOpen"
      :propform="rejectform"
    ></rejectDia>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
  
<script>
import { isManager } from "@/utils/auth";
import {
  copyCourseTemporary,
  CourseTemporaryisProfessional,
  copyCourse,
  listPost_course,
  listCourseTemporary,
  editCourseTemporary,
  revokeCourseTemporary,
  delCourseTemporary,
  submitCourseTemporary,
  getPost_course,
  delPost_course,
  addPost_course,
  updatePost_course,
  orderCourseList,
  reviewCourseTemporarybeforeCheck,
} from "@/api/course/course";
import {
  listPost_teacher,
  getCreatorList,
} from "@/api/schoolOrganization/teacher";
import { listPost_reviewConfig } from "@/api/configuration/auditConfiguration";
import rejectDia from "./components/rejectDia.vue";

import { listPost } from "@/api/system/post";
export default {
  name: "Course",
  dicts: ["sys_normal_disable"],
  components: { rejectDia },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位选项
      postOptions: [],
      // 岗位表格数据
      postList: [],
      // level
      level: [],
      status: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postIds: undefined,
        creatorName: undefined,
        courseName: undefined,
        status: "",
        dataScope: "0",
        schoolId: undefined,
      },
      //   教师列表
      teachers: [],
      creatorList: [],
      rejectOpen: false,
      rejectform: {},
      // 获取配置 是否品控和培训都关闭了审核课程环节
      needStep1: false,
      needStep2: false,

      isProfessional: false,
    };
  },
  activated() {
    this.getList();
  },
  async created() {
    await this.isProfessionalId();
    this.getList();
    this.getPostList();
    this.getAuditConfig();
  },
  methods: {
    /* 检测是否时专业人员 */
    async isProfessionalId() {
      try {
        let res = await CourseTemporaryisProfessional(
          this.$store.getters.userId
        );
        if (res.code == 200) {
          this.isProfessional = res.data;
        }
      } finally {
      }
    },

    isManager(e) {
      return isManager(e);
    },
    /* 获取课程审核配置 */
    async getAuditConfig() {
      let res = await listPost_reviewConfig({ reviewItem: 0 });
      this.needStep1 = res.rows[0].status == 1 ? false : true;
      this.needStep2 = res.rows[1].status == 1 ? false : true;
    },
    // 获取列表
    getList() {
      this.loading = true;
      let queryParams = { ...this.queryParams };
      if (
        this.$store.getters.roles.length == 1 &&
        this.$store.getters.roles[0] == "user" &&
        !this.isProfessional
      ) {
        queryParams.dataScope = "1";
      }
      listCourseTemporary(queryParams).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;

        this.$nextTick(() => {
          const refs = this.$refs;
          for (let key in refs) {
            if (
              key.includes("drop") &&
              refs[key] &&
              refs[key].menuItemsArray.length == 0
            ) {
              refs[key].$el.style.display = "none";
            }
          }
        });
        this.$forceUpdate();
      });
    },
    /* 获取岗位 */
    getPostList() {
      listPost({
        pageNum: 1,
        pageSize: 9999,
      }).then((response) => {
        this.postOptions = response.rows;
      });
    },
    /* 操作---------------------------- */
    /* !!!提交字眼的判断  返回是 提交审核还是同步到正式课*/
    /* type 有lable用于显示 同步到正式课/审核，show用于显示按钮是否存在 */
    returnSubmit(row, type) {
      // 不论是谁 只有自己能提交审核（这里需要从高级到低级判断）
      if (row.creatorId == this.$store.getters.userId) {
        // 如果是总经理创建
        if (
          this.$store.getters.roles.includes("dgm") ||
          this.$store.getters.roles.includes("gm")
        ) {
          return type == "lable" ? "同步至平台" : true;
        }
        // 如果是品控经理创建的
        else if (this.$store.getters.roles.includes("qcm")) {
          return type == "lable" ? "提交审核" : true;
        }
        // 如果是品控专员/培训专员创建
        else if (
          this.$store.getters.roles.includes("qcs") ||
          this.$store.getters.roles.includes("ts")
        ) {
          // 如果后面的配置全部关闭
          if (!this.needStep2) {
            return type == "lable" ? "同步至平台" : true;
          } else {
            return type == "lable" ? "提交审核" : true;
          }
        }
        // 如果是普通员工创建
        else {
          // 如果后面的配置全部关闭
          if (!this.needStep1 && !this.needStep2) {
            return type == "lable" ? "同步至平台" : true;
          } else {
            return type == "lable" ? "提交审核" : true;
          }
        }
      }
      // 如果不是自己则无法提交审核
      else {
        return type == "lable" ? "" : false;
      }
    },
    /* 提交审核 */
    async handleSubmitAudit(row, lable) {
      const loading = this.$loading({
        lock: true,
        text: "正在处理…",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let res;
        res = await submitCourseTemporary(row.id, 1);
        if (res.code == 200) {
          this.$modal.msgSuccess(`${lable}成功`);
          this.getList();
        }
      } finally {
        loading.close();
      }
    },
    /* 撤销提交审核操作 */
    async handleCancelAudit(row) {
      this.$confirm(
        `确认撤销【${row.courseName}】的审核申请吗?撤销后如需审核，需要重新提交审核申请！`,
        "撤销审核确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const loading = this.$loading({
            lock: true,
            text: "正在处理…",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          try {
            let res = await submitCourseTemporary(row.id, 0);
            if (res.code == 200) {
              this.$modal.msgSuccess(`撤销审核成功`);
              this.getList();
            }
          } finally {
            loading.close();
          }
        })
        .catch(() => {});
    },
    /* !!!审核按钮 根据角色是否显示*/
    returnAudit(row) {
      // 如果在专业人员审核
      if (row.status == 2 && row.professionalId == this.$store.getters.userId) {
        return true;
      }
      // 如果是培训专员/品控专员
      else if (
        row.status == 1 &&
        (this.$store.getters.roles.includes("qcs") ||
          this.$store.getters.roles.includes("ts"))
      ) {
        return true;
      }
      // 如果是品控经理
      else if (row.status == 3 && this.$store.getters.roles.includes("qcm")) {
        return true;
      }
      // 如果是总经理副总经理
      else if (
        row.status == 4 &&
        this.$store.getters.roles.includes("dgm") &&
        row.isDgmApproval == 1
      ) {
        console.log("如果是总经理副总经理");
        return true;
      } else {
        return false;
      }
    },
    /* 审核操作 */
    async handleAudit(row) {
      try {
        let before = await reviewCourseTemporarybeforeCheck({
          courseTemporaryId: row.id,
        });
        if (before.code == 200) {
          this.$router.push({
            path: "/course/officialCourseDetail",
            query: {
              courseTemporaryId: row.id,
              type: "audit",
              status: "temporary" + row.status,
            },
          });
        }
      } catch (error) {}
    },
    /* 驳回原因 */
    handleReason(row) {
      this.rejectform = row;
      this.rejectOpen = true;
    },
    /* 复制 只能复制草稿*/
    handleCopy(row) {
      this.$confirm(`确定复制吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const loading = this.$loading({
            lock: true,
            text: "加载中",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.6)",
          });
          try {
            let res = await copyCourseTemporary({
              id: row.id,
            });
            if (res.code == 200) {
              this.$modal.msgSuccess("复制成功");
              this.getList();
            }
          } finally {
            loading.close();
          }
        })
        .catch(() => {});
    },

    // 状态选择 查询列表
    handleSelect(key, keyPath) {
      this.queryParams.status = key;
      this.getList();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm(
        `确定删除【${row.courseName}】吗?删除后不可恢复！`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          await delCourseTemporary(ids);
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/course/addCourse",
        query: {
          type: "add",
        },
      });
    },
    /* 数据详情按钮 */
    handleDateDetail(row) {
      this.$router.push({
        path: "/course/courseDataDetail",
        query: {
          courseId: row.courseId,
          schoolCourseId: row.schoolCourseId,
        },
      });
    },
    /* 编辑课程 */
    handleEdit(item) {
      if (item.status == 5 || item.status == -1) {
        this.$confirm(
          `确定编辑【${item.courseName}】吗?编辑后将返回待提交`,
          "编辑确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            let data = { ...item };
            data.status = 2;
            await editCourseTemporary(data);
            this.$router.push({
              path: "/course/addCourse",
              query: {
                type: "edit",
                courseTemporaryId: item.id,
              },
            });
          })
          .catch(() => {});
      } else {
        this.$router.push({
          path: "/course/addCourse",
          query: {
            type: "edit",
            courseTemporaryId: item.id,
          },
        });
      }
    },
    /** 课程详情 */
    handleUpdate(row, type, status) {
      this.$router.push({
        path: "/course/officialCourseDetail",
        query: {
          courseTemporaryId: row.id,
          type: type,
          status: "temporary" + status,
        },
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
  <style scoped lang="scss">
.radio {
}
::v-deep .el-menu-item:hover {
  border-bottom: 1px solid #e6e6e6 !important;
}

::v-deep .el-menu--horizontal > .el-menu-item.is-active:hover {
  border-bottom: 2px solid #11a983 !important;
}
</style>
  